package ink.metoo.auto.fishpi.chatroom.handler.redpacket

import com.google.gson.Gson
import ink.metoo.auto.fishpi.Log
import ink.metoo.auto.fishpi.Settings
import ink.metoo.auto.fishpi.call.ChatRoomCall
import ink.metoo.auto.fishpi.chatroom.ChatRooms
import ink.metoo.auto.fishpi.chatroom.Message
import ink.metoo.auto.fishpi.chatroom.RedPacket

class SpecifyRedPacketHandler : RedPacketHandler {

    private val gson = Gson()

    override val types = arrayOf(RedPacket.Type.SPECIFY)

    override fun handle(message: Message, redPacket: RedPacket) = try {
        val recivers = toRecivers(redPacket)
        if (recivers.contains(Settings.fishpiClient.username)) {
            ChatRoomCall.openRedPacket(message.oId!!)
        }
        Unit
    } catch (e: Exception) {
        Log.error(e.message, e)
    }

    private fun toRecivers(redPacket: RedPacket): Array<String> {
        val reciversStr = redPacket.recivers
        val recivers = gson.fromJson(
            reciversStr.replace("\\", ""),
            Array<String>::class.java
        )
        return recivers
    }

    override fun receivedStatusHandle(message: Message, redPacket: RedPacket) {
        val recivers = toRecivers(redPacket).joinToString(", ")
        val whoGot = message.whoGot
        if (whoGot != null) {
            val whoGotReceivedInfo = redPacket.who.findLast { it.userName == whoGot } ?: return
            message.userName = message.whoGive
            message.time = whoGotReceivedInfo.time
            ChatRooms.console(
                message,
                "【${redPacket.typeEnum.description}】 ${redPacket.msg} [$recivers] - ${redPacket.money}(${redPacket.got}/${redPacket.count}) <${whoGotReceivedInfo.userName}> ${whoGotReceivedInfo.userMoney}"
            )
        } else {
            val receivedInfo = redPacket.who.joinToString(", ", prefix = "[", postfix = "]") { "<${it.userName}> ${it.userMoney}" }
            ChatRooms.console(
                message,
                "【${redPacket.typeEnum.description}】 ${redPacket.msg} [$recivers] - ${redPacket.money}(${redPacket.got}/${redPacket.count}) $receivedInfo"
            )
        }
    }
}